
Imports DotNetNuke.Entities.Portals
Imports DotNetNuke.Entities.Modules
Imports DotNetNuke.Security

Namespace RTP.HTMLNewsletter
    Public MustInherit Class HTMLNewsletter
        Inherits NewsletterBase
        Implements Entities.Modules.IActionable

#Region "Private Members"
#End Region

#Region "Event Handlers"

        'This call is required by the Web Form Designer.
        <DebuggerStepThrough()> Private Sub InitializeComponent()

        End Sub

        Private Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Init
            'CODEGEN: This method call is required by the Web Form Designer
            'Do not modify it using the code editor.
            InitializeComponent()
        End Sub

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As EventArgs) Handles MyBase.Load

            Dim editVisibility As Boolean
            editVisibility = DisplayIcons()

            If (Not Page.IsPostBack) Then
                Localization.LocalizeGridView(dgPNL, LocalResourceFile)
                btnNewNewsletter.AlternateText = Localization.GetString("NewNewsletter", LocalResourceFile)
                btnNewNewsletter.ToolTip = Localization.GetString("NewNewsletter", LocalResourceFile)

                If (Request.Params("ViewID") <> "") Then
                    If (Request.Params("Page") <> "") Then
                        dgPNL.PageIndex = CInt(Request.Params("Page")) - 1
                    End If
                    pnlModuleContent.Visible = True
                    DrawHTMLContent(CInt(Request.Params("ViewID")))
                Else
                    pnlModuleContent.Visible = False
                End If

                BindDataGrid(editVisibility)

            End If

        End Sub

        Private Sub btnNewNewsletter_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNewNewsletter.Click
            Response.Redirect(EditUrl("Edit"))
        End Sub

        Private Sub cmdNewNewsletter_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdNewNewsletter.Click
            Response.Redirect(EditUrl("Edit"))
        End Sub

        Private Sub dgPNL_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles dgPNL.PageIndexChanging
            'Set page index
            dgPNL.PageIndex = e.NewPageIndex

            'Binddata
            Dim editVisibility As Boolean
            editVisibility = DisplayIcons()

            BindDataGrid(editVisibility)

        End Sub

        Private Sub dgPNL_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dgPNL.RowCommand
            Try
                Select Case e.CommandName
                    Case "Edit"
                        'set selected row editable
                        Dim iItemID As Long = CType(e.CommandArgument, Integer)
                        Response.Redirect(EditUrl("ItemID", iItemID.ToString))
                End Select
            Catch exc As Exception 'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        Private Sub dgPNL_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgPNL.RowCreated
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim tooltipTitle As String = CType(DataBinder.Eval(e.Row.DataItem, "NewsletterDesc"), String)
                Dim tooltipBody As String = CType(DataBinder.Eval(e.Row.DataItem, "NewsletterBody"), String)
                Dim lnkNl As HyperLink = CType(e.Row.FindControl("Title"), HyperLink)
                lnkNl.Attributes.Add("title", "<table class=""HTMLNtooltiptable""><tr><td class=""HTMLNtooltipheader"">" + tooltipTitle + "</td></tr><tr><td class=""HTMLNtooltipbody"">" + tooltipBody + "</td></tr></table>")
            End If
        End Sub

        Private Sub dgPNL_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgPNL.RowDataBound
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim lnkNl As HyperLink = CType(e.Row.FindControl("Title"), HyperLink)
                toolTipManager.TargetControls.Add(lnkNl.ClientID, True)
            End If
        End Sub

        Private Sub dgPNL_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles dgPNL.RowEditing

        End Sub

#End Region

#Region "Public Methods"
        Public Function ViewNewsletter(ByVal newsletterID As Integer) As String
            Dim url As String = NavigateURL()
            Dim addPar As String = "?"
            If InStr(url, "?") > 0 Then
                addPar = "&"
            End If
            url = url & addPar & "ViewID=" & NewsletterID.ToString & "&Page=" & (dgPNL.PageIndex + 1).ToString
            Return url
            '            Return NavigateURL("View", "ViewID", NewsletterID.ToString, "Page", (dgPNL.PageIndex + 1).ToString)
        End Function

        Public Function ShowDate(ByVal theDate As Date) As String
            Dim outputStr As String = String.Format("{0:g}", theDate)
            Return outputStr
        End Function
#End Region

#Region "Private Methods "
        Private Sub BindDataGrid(ByVal editvisibility As Boolean)
            Dim objCtlNewsletter As New NewsletterController
            Dim sqlDr As ArrayList
            If Not editvisibility Then
                sqlDr = objCtlNewsletter.GetNewslettersByUserID(Int32.Parse(UserInfo.UserID.ToString), PortalId, UserInfo.IsInRole("Administrators"))
            Else
                sqlDr = objCtlNewsletter.GetNewslettersForEdit(ModuleId)
            End If

            Dim colNewsletters As New ArrayList

            Dim footerTemplate As String = ""
            Dim objNewsletter As NewsletterInfo

            Dim tzi As TimeZoneInfo = GetTimeZoneInfo()

            For Each objNewsletter In sqlDr
                If Not objNewsletter.FooterTemplate Is Nothing Then
                    footerTemplate = System.Web.HttpUtility.HtmlDecode(objNewsletter.FooterTemplate)
                End If
                objNewsletter.EditVisibility = editvisibility
                If objNewsletter.NewsletterBody.ToLower.Contains("[user:") Or objNewsletter.NewsletterBody.ToLower.Contains("[profile:") Then
                    Dim trn As New Services.Tokens.TokenReplace(Services.Tokens.Scope.DefaultSettings, ModuleId)
                    objNewsletter.NewsletterBody = trn.ReplaceEnvironmentTokens(objNewsletter.NewsletterBody)
                End If
                objNewsletter.DateUpdated = TimeZoneInfo.ConvertTimeFromUtc(objNewsletter.DateUpdated, tzi)
                objNewsletter.DateCreated = TimeZoneInfo.ConvertTimeFromUtc(objNewsletter.DateCreated, tzi)
                objNewsletter.PublishDate = TimeZoneInfo.ConvertTimeFromUtc(objNewsletter.PublishDate, tzi)
                colNewsletters.Add(objNewsletter)
            Next

            dgPNL.DataKeyNames = New String() {"NewsletterID"}
            dgPNL.DataSource = colNewsletters
            dgPNL.DataBind()

            divitcFooter.InnerHtml = footerTemplate

        End Sub

        Private Function GetTimeZoneInfo() As TimeZoneInfo
            'Get the portalTimeZone as a fallback
            Dim tzi As TimeZoneInfo = PortalController.GetCurrentPortalSettings.TimeZone

            Try
                'Get the userTime based on user profile preference if user is authenticated
                If System.Web.HttpContext.Current.Request.IsAuthenticated Then
                    Dim objUser As UserInfo = UserController.GetCurrentUserInfo
                    tzi = objUser.Profile.PreferredTimeZone
                End If
            Catch
            End Try

            Return tzi
        End Function

        Private Function DisplayIcons() As Boolean
            dgPNL.Columns.Item(3).Visible = False
            NewsletterIcons.Visible = False
            NewsletterIcons.Height = "0px"
            Dim editVisibility As Boolean = False
            If Request.IsAuthenticated() Then
                Dim objModuleController As New ModuleController
                Dim objModuleInfo As ModuleInfo = objModuleController.GetModule(ModuleId, TabId)
                If DotNetNuke.Security.Permissions.ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "EDIT", objModuleInfo) Then
                    NewsletterIcons.Visible = True
                    NewsletterIcons.Height.Remove(0)
                    editVisibility = True
                    dgPNL.Columns.Item(3).Visible = True
                End If
            End If

            Return editVisibility
        End Function

        Private Sub DrawHTMLContent(ByVal nlID As Integer)
            Dim objCtlNewsletter As New NewsletterController
            Dim objNewsletter As NewsletterInfo = objCtlNewsletter.GetNewsletterbyID(nlID)
            If Not objNewsletter Is Nothing Then
                If objNewsletter.NewsletterBody.ToLower.Contains("[user:") Or objNewsletter.NewsletterBody.ToLower.Contains("[profile:") Then
                    Dim trn As New Services.Tokens.TokenReplace(Services.Tokens.Scope.DefaultSettings, ModuleId)
                    objNewsletter.NewsletterBody = trn.ReplaceEnvironmentTokens(objNewsletter.NewsletterBody)
                End If
                HtmlHolder.InnerHtml = "<h1>" & objNewsletter.NewsletterDesc & "</h1>"
                HtmlHolder.InnerHtml += Server.HtmlDecode(objNewsletter.NewsletterBody)
            End If
        End Sub

#End Region

#Region "Optional Interfaces"

        Public ReadOnly Property ModuleActions() As Entities.Modules.Actions.ModuleActionCollection Implements Entities.Modules.IActionable.ModuleActions
            Get
                ' ReSharper disable LocalVariableHidesMember
                ' ReSharper disable InconsistentNaming
                Dim Actions As New Entities.Modules.Actions.ModuleActionCollection
                ' ReSharper restore InconsistentNaming
                ' ReSharper restore LocalVariableHidesMember
                Actions.Add(GetNextActionID(), Localization.GetString("EditNews", LocalResourceFile), "", "", "", EditUrl("Edit"), False, DotNetNuke.Security.SecurityAccessLevel.Edit, True, False)
                Return Actions
            End Get
        End Property

#End Region

    End Class

End Namespace